package com.aote.util;

import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;

import com.browsesoft.Tools;
import com.browsesoft.hibernate.HibernateUtil;
import com.browsesoft.htmlcomponent.HTMLPage;
import com.browsesoft.user.User;
import com.browsesoft.util.SessionHelper;

/**
 * 页面出来工具
 */
public class PageHelper {
	/**
	 * 根据请求查找，产生页面
	 */
	public static void getPage(HttpServletRequest request,
			HttpServletResponse response) {
		Session hibSession = HibernateUtil.getSessionFactory()
				.getCurrentSession();
		hibSession.beginTransaction();
		try {
			HttpSession session = request.getSession();
			Writer out = response.getWriter();
			if (isTimeOut(request, response)) {
				String outStr = "<body onload=\"window.open('page.jsp?templatename=time_out','_top');\" />";
				out.write(outStr);
				return;
			}
			HTMLPage p = null;
			// 移走session中超时的页面
			Tools.removeHTMLPage(session);
			// 模板名字
			String templateName = request.getParameter("templatename");
			// 有模板，说明第一次进入，生成页面
			if (templateName != null) {
				p = getPage(request, templateName);
			}
			// 否则，在session中找
			else {
				// 根据页面名在session中找到页面
				String name = (String) request.getParameter("pagename");
				p = SessionHelper.getPage(session, name);
			}
			// 页面处理请求
			if (p == null) {
				String outStr = "<body onload=\"window.open('page.jsp?templatename=time_out','_top');\" />";
				out.write(outStr);
				return;
			}
			String html = p.disposePage(request, response);
			out.write(html);
			if (hibSession.isOpen()) {
				hibSession.getTransaction().commit();
			}
		} catch (Exception e) {
			if (hibSession.isOpen()) {
				hibSession.getTransaction().rollback();
			}
			e.printStackTrace();
		}

	}

	public static HTMLPage getPage(HttpServletRequest request,
			String templateName) throws Exception {
		HTMLPage p;
		p = new HTMLPage(null);
		// 加载模板
		p.setTemplateName(request, templateName);
		// 往session中添加新的页面
		SessionHelper.putPage(request, p);
		return p;
	}
	
	

	/**
	 * @throws Exception
	 * 
	 */
	private static boolean isTimeOut(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String templateName = (String) request.getParameter("templatename");
		if (templateName != null
				&& (templateName.equals("login") || templateName
						.equals("time_out"))) {
			return false;
		}
		// 检查是否超时
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("loginUser");
		// 超时
		if (user == null) {
			return true;
		}
		return false;
	}

	/**
	 * @throws Exception
	 * 
	 */
	public static String getPageContent(HttpServletRequest request,
			HttpServletResponse response, String templateName) throws Exception {
		HTMLPage p = getPage(request, templateName);
		String result = p.disposePage(request, response);
		return result;

	}
}
